<?php 
Class Ws{
    
    CONST HOST ="0.0.0.0";
    CONST PORT =8811;
    
    public $ws=null;
    public  function __construct(){
        $this->ws =new swoole_websocket_server("0.0.0.0",8811);
        
        
        $this->ws->set(
            [
               'worker_num'=>2,
                'task_worker_num' =>2,
            ]);
        $this->ws->on("open",[$this,'onOPen']);
        $this->ws->on("message",[$this,'onMessage']);
        $this->ws->on("task",[$this,'onTask']);
        $this->ws->on("finish",[$this,'onFinish']);
        $this->ws->on("close",[$this,'onClose']);
        
        $this->ws->start();
        
    }   
    
    //监听
    public  function  onOpen($ws,$request){
        $GLOBALS['fd'][0] =$request->fd;
        if($request->fd>=1){
            //每两秒执行一次
            swoole_timer_tick(2000,function($timer_id) use ($ws,$request) {
                echo "2S: timerId: $timer_id";
                   $zhi=time();
                $ws->push($request->fd,"恭喜你了哈哈！$zhi");
                
            });
        }
        var_dump($request->fd);
    }
    //监听消息事件
    public  function onMessage($ws,$request){
        echo "有新的消息 $request->data";
            
        swoole_timer_after(5000,function() use ($ws,$request) {
          echo "5S After";
          $ws->push($request->fd,"来自5秒钟之后的消息");
        });
//         $data=[
//             'task'=>"123",
//             'fd'=>$request->fd,
//         ];
//        $ws->task($data);
//        echo "分割线------";
       
        $ws->push($request->fd,$request->data);
    }
    
    public function onTask($serv,$taskId,$workerId,$data){
//             var_dump($data);
            //耗时的场景
            sleep(10);
            return "Task 完成";
    }
    
    public function onFinish($serv,$taskId,$Tasedata){
            echo "TaskId $taskId \n";
            echo "Sucess $Tasedata";
            $this->ws->push($GLOBALS['fd'][0],"Task OK");
    }
    
    //关闭事件
    public function onClose($ws,$fd){
        echo "关闭 $fd";
    }
}

$n=new Ws();